//
//  SearchTableViewController.m
//  YanMusicPlayer
//
//  Created by 1564335 on 15-6-16.
//  Copyright (c) 2015年 胡岩 All rights reserved.
//

#import "SearchTableViewController.h"
#import "SingerMusicListModel.h"
#import "SingerMusicListTableViewCell.h"
#import "SongListViewController.h"
@interface SearchTableViewController ()<UITableViewDataSource, UITableViewDelegate, changeController>

@property(nonatomic, strong) NSMutableArray *arrayData;

@property(nonatomic, strong) NSMutableArray *urlArray;

@property(nonatomic, strong) UITableView *mainTV;

@property(nonatomic, strong) UIActivityIndicatorView *activity;

@end

@implementation SearchTableViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    UIImageView *backgroundImageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, _WIDTH, _HEIGHT)];
    [self.view addSubview:backgroundImageView];
    UIBlurEffect *effect = [UIBlurEffect effectWithStyle:UIBlurEffectStyleLight];
    UIVisualEffectView *backgroundView = [[UIVisualEffectView alloc] initWithEffect:effect];
    backgroundView.frame = CGRectMake(0, 0, _WIDTH, _HEIGHT);
    [self.view addSubview:backgroundView];
    [backgroundImageView setImage:[UIImage imageNamed:@"bgImage2"]];
    
    self.view.backgroundColor = [UIColor clearColor];
    _arrayData = [NSMutableArray array];
    self.navigationItem.title = _url;
    [self netWork];
    
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 15, _WIDTH, 50)];
    view.backgroundColor = [UIColor clearColor];
    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
    button.frame = CGRectMake(10, 15, 30, 30);
    [button setImage:[UIImage imageNamed:@"iconfont-fanhui"] forState:UIControlStateNormal];
    [button addTarget:self action:@selector(backFromSelf) forControlEvents:UIControlEventTouchUpInside];
    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(50, 0, _WIDTH - 100, view.frame.size.height)];
    label.textAlignment = NSTextAlignmentCenter;
    label.text = _url;
    [view addSubview:button];
    [view addSubview:label];
    [self.view addSubview:view];
    
    _activity = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge];
    [self.view addSubview:_activity];
    [_activity startAnimating];
    _activity.center = self.view.center;
    
}

- (void)initTableView
{
    _mainTV = [[UITableView alloc] initWithFrame:CGRectMake(0, 70, _WIDTH, _HEIGHT - 100) style:UITableViewStylePlain];
    _mainTV.delegate = self;
    _mainTV.dataSource = self;
    _mainTV.backgroundColor = [UIColor clearColor];
    _mainTV.separatorStyle = UITableViewCellSeparatorStyleNone;
    _mainTV.showsVerticalScrollIndicator = NO;
    [self.view addSubview:_mainTV];
}

- (void)netWork
{
    NSString *path = [[URLPath searchURL] stringByAppendingFormat:@"%@&size=50", _url];
    path = [path stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    [manager GET:path parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
        
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:operation.responseData options:NSJSONReadingMutableContainers error:nil];
        NSArray *array = dic[@"data"];
        _urlArray = [NSMutableArray array];
        for (NSDictionary *dic in array) {
            SingerMusicListModel *model = [[SingerMusicListModel alloc] initWithDic:dic];
            [self.arrayData addObject:model];
            MusicModel *musicModel = [MusicModel getMusicModel];
            musicModel.url = model.url;
            musicModel.singerName = model.singer_name;
            musicModel.songName = model.song_name;
            musicModel.lrcId = model.song_id;
            musicModel.singerId = model.singer_id;
            musicModel.songId = model.song_id;
            musicModel.musicLength = model.duration;
            [_urlArray addObject:musicModel];
        }
        [_activity stopAnimating];
        [self initTableView];
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        [_activity stopAnimating];
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"网络连接失败!" message:nil delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        [alert show];
        
    }];
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *identifier = @"cell";
    SingerMusicListTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
    if (cell == nil) {
        cell = [[SingerMusicListTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
    }
    SingerMusicListModel *model = [self.arrayData objectAtIndex:indexPath.row];
//    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    
    [cell.collectBtn addTarget:self action:@selector(collect:) forControlEvents:UIControlEventTouchUpInside];
//    [cell.downloadBtn addTarget:self action:@selector(download:) forControlEvents:UIControlEventTouchUpInside];
    cell.collectBtn.tag =  indexPath.row;
    cell.downloadBtn.tag = indexPath.row;
    cell.singerDelegate = self;

    if (indexPath.row % 2 == 0) {
        cell.contentView.backgroundColor = [UIColor colorWithRed:227/255.0 green:233/255.0 blue:240/255.0 alpha:1];
    } else {
        cell.contentView.backgroundColor = [UIColor clearColor];
    }

    
    NSArray *array = [Database selectData:@""];
    NSArray *downloadArray = [Database selectDownloadData];
    BOOL isOK = YES;
    BOOL isDownLoad = YES;
    for (MusicModel *downloadModel in downloadArray) {
        if ([downloadModel.songId integerValue] == [model.song_id integerValue]) {
            cell.downloadImage = @"iconfont-xiazaiwancheng";
            isDownLoad = NO;
            break;
        }
    }
    if (isDownLoad) {
        cell.downloadImage = @"iconfont-xiazai2";
    }
    
    for (MusicModel *dbModel in array) {
        if ([dbModel.songId integerValue] == [model.song_id integerValue]) {
            cell.collectImage = @"iconfont-xihuan";
            isOK = NO;
            break;
        }
    }
    if (isOK) {
        cell.collectImage = @"iconfont-xihuan3";
    }
    [cell setSingerMusicListModel:model];
    return cell;
}

- (void)changeController
{
    SongListViewController *song = [[SongListViewController alloc] init];
    [self presentViewController:song animated:YES completion:^{
        [song addTable];
    }];
}

#pragma -mark 收藏
- (void)collect:(UIButton *)button
{
    MusicModel *model = [_urlArray objectAtIndex:button.tag];
    NSArray *array = [Database selectData:@""];
    BOOL isOK = YES;
    for (MusicModel *dbModel in array) {
        if ([dbModel.songId integerValue] == [model.songId integerValue]) {
            isOK = NO;
            break;
        }
    }
    if (isOK) {
        NSIndexPath *indexPath = [NSIndexPath indexPathForRow:button.tag inSection:0];
        SingerMusicListTableViewCell *cell = [_mainTV cellForRowAtIndexPath:indexPath];
        
        cell.collectImage = @"iconfont-xihuan";
        [_mainTV reloadData];
        [[MusicPlayer1 shareInstance].collectList addObject:model];
        [Database insertValue:model];
    } else {
        NSIndexPath *indexPath = [NSIndexPath indexPathForRow:button.tag inSection:0];
        SingerMusicListTableViewCell *cell = [_mainTV cellForRowAtIndexPath:indexPath];
        
        cell.collectImage = @"iconfont-xihuan3";
        [_mainTV reloadData];
        [Database deleteValue:model.songId];
        NSArray *array = [Database selectData:@""];
        [[MusicPlayer1 shareInstance].collectList removeAllObjects];
        [[MusicPlayer1 shareInstance].collectList addObjectsFromArray:array];
    }
    if ([HearderView shareInstance].currentList == 0) {
        [[MusicPlayer1 shareInstance].list removeAllObjects];
        [[MusicPlayer1 shareInstance].list addObjectsFromArray:[MusicPlayer1 shareInstance].collectList];
        [[HearderView shareInstance].listTableView reloadData];
    }
}

#pragma -mark 下载
- (void)download:(UIButton *)button
{
    SingerMusicListModel *model = [self.arrayData objectAtIndex:button.tag];
    NSArray *array = [Database selectDownloadData];
    BOOL isHave = NO;
    for (MusicModel *musicModel in array) {
        if ([model.song_id integerValue] == [musicModel.songId integerValue]) {
            isHave = YES;
        }
    }
    
    if (!isHave) {
        [UIView animateWithDuration:0.8 animations:^{
            button.frame = CGRectMake(_WIDTH - 30, 20, 10, 10);
        } completion:^(BOOL finished) {
            
        }];
        AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
        manager.responseSerializer = [AFHTTPResponseSerializer serializer];
        [manager GET:model.url parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
            NSString *number = [_USERDEFAULT objectForKey:@"number"];
            NSString *musicName = [NSString stringWithFormat:@"music%@.mp3", number];
            MusicModel *musicModel = [MusicModel getMusicModel];
            musicModel.url = musicName;
            musicModel.singerName = model.singer_name;
            musicModel.songName = model.song_name;
            musicModel.lrcId = model.song_id;
            musicModel.singerId = model.singer_id;
            musicModel.songId = model.song_id;
            musicModel.musicLength = model.duration;
            [Database insertDownloadValue:musicModel];
            [[MusicPlayer1 shareInstance].downloadList addObject:model];
            
            if ([HearderView shareInstance].currentList == 1) {
                [[MusicPlayer1 shareInstance].list removeAllObjects];
                [[MusicPlayer1 shareInstance].list addObjectsFromArray:[MusicPlayer1 shareInstance].downloadList];
                [[HearderView shareInstance].listTableView reloadData];
            }
            
            NSString *musicPath = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:musicName];
            
            [[NSFileManager defaultManager] createFileAtPath:musicPath contents:operation.responseData attributes:nil];
            NSInteger num = [number integerValue];
            number = [NSString stringWithFormat:@"%ld", ++num];
            [_USERDEFAULT setObject:number forKey:@"number"];
            [UIView animateWithDuration:0.8 animations:^{
                [_mainTV reloadData];
                button.frame = CGRectMake(_WIDTH - 40, 15, 50 - 30, 50 - 30);
            } completion:^(BOOL finished) {
                
            }];
            
        } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
            [UIView animateWithDuration:0.8 animations:^{
                button.frame = CGRectMake(_WIDTH - 40, 15, 50 - 30, 50 - 30);
            } completion:^(BOOL finished) {
                UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"下载失败" message:nil delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
                [alert show];
            }];
            
        }];
    } else {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"已经下载" message:nil delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        [alert show];
    }
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.arrayData.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 50;
}

- (void)backFromSelf
{
    [self dismissViewControllerAnimated:YES completion:^{
        
    }];
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [HearderView shareInstance].currentList = 100;
    [MusicPlayer1 shareInstance].isDownLoadList = NO;
    [MusicPlayer1 shareInstance].isDownLoad = NO;
    [[MusicPlayer1 shareInstance] loadMusicList:_urlArray];
    SingerMusicListModel *model = [self.arrayData objectAtIndex:indexPath.row];
    [MusicPlayer1 shareInstance].firstPlay = YES;
    [[MusicPlayer1 shareInstance].moviePlayer setContentURL:[NSURL URLWithString:model.url]];
    [MusicPlayer1 shareInstance].isPlay = YES;
    [[HearderView shareInstance].startButton setImage:[UIImage imageNamed:@"pause"] forState:UIControlStateNormal];
    [MusicPlayer1 shareInstance].currentMusic = indexPath.row;
    [[MusicPlayer1 shareInstance] play];
    [[HearderView shareInstance].listTableView reloadData];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
